﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Xml.Linq;
using System.Windows;
using System.IO;
using System.Reflection;

namespace WebPythonHost
{
  class Program
  {
    [STAThread]
    public static void Main()
    {
      try
      {
        var textWriter = new StreamWriter(ApplicationHlp.MapPath("log.html"));
        var traceListener = new System.Diagnostics.TextWriterTraceListener(textWriter);
        traceListener.WriteLine(@"<html><head><meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8""/></head><body>");
        traceListener.Flush();
        Trace.AutoFlush = true;
        Trace.Listeners.Add(traceListener);
        Run();
      }
      catch (Exception exc)
      {
        Trace.WriteLine(exc);
      }
    }

    static void Run()
    {
      var knowledge = GetFileOrResource("knowledge/knowledge.yaml");
      var test_knowledge = GetFileOrResource("knowledge/test_knowledge.yaml");
      var executor = GetFileOrResource("knowledge/executor.py");
      var host = new PythonHost(knowledge, test_knowledge, executor);
      host.ExecuteKnowledgePiece("start from .net host", null);
    }

    static string GetFileOrResource(string relativePath)
    {
      var path = ApplicationHlp.MapPath(relativePath);
      if (File.Exists(path))
      {
        return File.ReadAllText(path);
      }
      var resourceStreamInfo = Application.GetResourceStream(new Uri(relativePath, UriKind.RelativeOrAbsolute));
      if (resourceStreamInfo != null)
      {
        var content = new StreamReader(resourceStreamInfo.Stream).ReadToEnd();
        return content;
      }
      var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(relativePath);
      if (resourceStream != null)
      {
        var content = new StreamReader(resourceStream).ReadToEnd();
        return content;
      }
      return null;
    }

  }
}
